﻿using FI.Core.IoC;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Compilation;
using System.Web.Hosting;

namespace Sample.Common
{
    public static class Utility
    {
        public static string TruncateField(string fieldName, int maxLength)
        {
            if (fieldName.Length > maxLength)
            {
                return fieldName.Remove(maxLength) + "...";
            }

            return fieldName;
        }

      

        private static string GetBaseDirectory()
        {
            if (HttpContext.Current == null)
            {
                return AppDomain.CurrentDomain.BaseDirectory;
            }

            return AppDomain.CurrentDomain.RelativeSearchPath;
        }

        public static dynamic GetDynamicObject(Dictionary<string, object> properties)
        {
            var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
            foreach (var property in properties)
            {
                dynamicObject.Add(property.Key, property.Value);
            }
            return dynamicObject;
        }


        public static string LookupResource(Type resourceType, string resourceKey)
        {
            var property = resourceType.GetProperties().FirstOrDefault(p => p.PropertyType == typeof(ResourceManager));
            return property != null ? ((ResourceManager)property.GetValue(null, null)).GetString(resourceKey) : resourceKey;
        }

        public static void ImportItems<TKey, TValue>(this IDictionary<TKey, TValue> dict, IDictionary<TKey, TValue> source)
        {
            foreach (var item in source)
            {
                dict.Add(item.Key, item.Value);
            }
        }

        public static string GetPropertyName(Expression lambdaExpression)
        {
            IList<string> list = new List<string>();
            var e = lambdaExpression;

            while (true)
            {
                switch (e.NodeType)
                {
                    case ExpressionType.Lambda:
                        e = ((LambdaExpression)e).Body;
                        break;
                    case ExpressionType.MemberAccess:
                        var propertyInfo = ((MemberExpression)e).Member as PropertyInfo;
                        var prop = propertyInfo != null
                            ? propertyInfo.Name
                            : null;
                        list.Add(prop);

                        var memberExpression = (MemberExpression)e;
                        if (memberExpression.Expression.NodeType != ExpressionType.Parameter)
                        {
                            var parameter = GetParameterExpression(memberExpression.Expression);
                            if (parameter != null)
                            {
                                e = Expression.Lambda(memberExpression.Expression, parameter);
                                break;
                            }
                        }
                        return string.Join(".", list.Reverse());
                    case ExpressionType.Convert:
                        var unaryExpression = e as UnaryExpression;
                        if (unaryExpression != null) e = (unaryExpression.Operand);
                        break;
                    default:
                        return null;
                }
            }
        }

        private static ParameterExpression GetParameterExpression(Expression expression)
        {
            while (expression.NodeType == ExpressionType.MemberAccess)
            {
                expression = ((MemberExpression)expression).Expression;
            }
            return expression.NodeType == ExpressionType.Parameter ? (ParameterExpression)expression : null;
        }

        public static string GetLoaderException(ReflectionTypeLoadException rex)
        {
            if (rex == null)
            {
                return string.Empty;
            }

            var loaderExceptions = rex.LoaderExceptions;
            if (loaderExceptions == null)
            {
                return string.Empty;
            }

            var builder = new StringBuilder();
            foreach (var item in loaderExceptions)
            {
                builder.AppendFormat("\t{0}\r\n", item.Message);
                builder.AppendLine();
            }

            return builder.ToString();
        }

        public static int ReverseStatus(string p)
        {
            switch (p)
            {
                case "Inactive": return 0;
                case "Active": return 1;
                case "Pending": return 2;
                case "Approved": return 3;
                default: return -1;
            }
        }

        public static string ConvertStatus(int i)
        {
            switch (i)
            {
                case 0: return "Inactive";
                case 1: return "Active";
                case 2: return "Pending";
                case 3: return "Approved";

                default: return "";

            }
        }
        public static string GetApplicationPath()
        {
            var serverUrl = System.Web.HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
            return serverUrl;
        }

        public static string GetAppServerAbsolutePath(HttpRequest request)
        {
            if (request == null || request.Url == null)
            {
                return string.Empty;
            }

            //string:http://loaclhost:123/xx/xxx/xxxx  
            var serverAbsoluteUri = request.Url.ToString().TrimEnd('/');
            //string:/xx/xxx/xxxx
            var absolutePath = request.FilePath.TrimEnd('/');
            var applicationPath = request.ApplicationPath.TrimEnd('/');
            //string:http://loaclhost:123
            var serverUrl = "";

            if (!string.IsNullOrEmpty(absolutePath))
            {
                //get string:http://loaclhost:123 from string:http://loaclhost:123/xx/xxx/xxxx 
                var index = serverAbsoluteUri.IndexOf(absolutePath);
                serverUrl = serverAbsoluteUri.Substring(0, index + applicationPath.Length);
            }
            else
            {
                serverUrl = serverAbsoluteUri;
            }
            return serverUrl;
        }

        //public static string GetCultureFromUrl(HttpRequest request)
        //{
        //    if (request == null)
        //    {
        //        return string.Empty;
        //    }

        //    var rawUrl = request.RawUrl;

        //    if (string.IsNullOrEmpty(rawUrl))
        //    {
        //        return string.Empty;
        //    }
        //    var key = string.Format("{0}=", RouteKeys.CultureKey);
        //    var index = rawUrl.IndexOf(key);
        //    if (index < 0)
        //    {
        //        return string.Empty;
        //    }

        //    var tempUrl = rawUrl.Substring(index + key.Length);
        //    var culture = string.Empty;
        //    var indexOfNexSplit = tempUrl.IndexOf("&");
        //    if (indexOfNexSplit < 0)
        //    {
        //        culture = tempUrl;
        //    }
        //    else
        //    {
        //        culture = tempUrl.Substring(0, tempUrl.Length - indexOfNexSplit);
        //    }

        //    var isValidCulture = CultureHelper.ValidateCulture(culture);
        //    if (!isValidCulture)
        //    {
        //        return string.Empty;
        //    }

        //    return culture;
        //}

        public static string GetThumbnailPath(string originalImagePath)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Path.GetFileNameWithoutExtension(originalImagePath)).Append("_tb").Append(Path.GetExtension(originalImagePath));

            return Path.Combine(Path.GetDirectoryName(originalImagePath), sb.ToString());


        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath"></param>
        /// <param name="thumbnailPath"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static string GenerateThumbnail(string originalImagePath)
        {

            int width = 427;
            int height = 640;

            string thumbnailPath = GetThumbnailPath(originalImagePath);


            //获取原始图片  
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            //缩略图画布宽高  
            int towidth = width;
            int toheight = height;
            //原始图片写入画布坐标和宽高(用来设置裁减溢出部分)  
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            //原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)  
            int bg_x = 0;
            int bg_y = 0;
            int bg_w = towidth;
            int bg_h = toheight;
            //倍数变量  
            double multiple = 0;
            //获取宽长的或是高长与缩略图的倍数  
            if (originalImage.Width >= originalImage.Height)
                multiple = (double)originalImage.Width / (double)width;
            else
                multiple = (double)originalImage.Height / (double)height;
            //上传的图片的宽和高小等于缩略图  
            if (ow <= width && oh <= height)
            {
                //缩略图按原始宽高  
                bg_w = originalImage.Width;
                bg_h = originalImage.Height;
                //空白部分用背景色填充  
                bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2);
                bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2);
            }
            //上传的图片的宽和高大于缩略图  
            else
            {
                //宽高按比例缩放  
                bg_w = Convert.ToInt32((double)originalImage.Width / multiple);
                bg_h = Convert.ToInt32((double)originalImage.Height / multiple);
                //空白部分用背景色填充  
                bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
                bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
            }
            //新建一个bmp图片,并设置缩略图大小.  
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板  
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法  
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            //设置高质量,低速度呈现平滑程度  
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并设置背景色  
            g.Clear(System.Drawing.ColorTranslator.FromHtml("#F2F2F2"));
            //在指定位置并且按指定大小绘制原图片的指定部分  
            //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素  
            g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //获取图片类型  
                string fileExtension = System.IO.Path.GetExtension(originalImagePath).ToLower();
                //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.  
                switch (fileExtension)
                {
                    case ".gif": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break;
                    case ".jpg": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break;
                    case ".bmp": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp); break;
                    case ".png": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break;
                }
                return thumbnailPath;
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();

            }
        }

    }
}
